package com.zyf.chapter02.structure.decorator.eureka;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 可伸缩客户端(随便翻译一下？)
 *  如果 eureka server 有多个，则选择 eureka server，从配置的第一个选起
 *  <p>defaultZone: http://admin:${jhipster.registry.password}@localhost:8761/eureka/,
 *  http://admin:${jhipster.registry.password}@localhost:8762/eureka/</p>
 * @author yifeng
 */
public class RetrableHttpClient extends HttpClientDecorator{
	private TransportClientFactory factory;

	private AtomicReference<HttpClient> delegate = new AtomicReference<>();
    public RetrableHttpClient(TransportClientFactory clientFactory) {
        this.factory = clientFactory;
    }

    @Override
    protected String execute(RequestExecutor executor) {
        System.out.println("Retrable 执行 execute 逻辑");
        if (delegate.get() == null) {
            delegate.set(factory.newClient());
        }
        return executor.execute(delegate.get());
    }

    public static HttpClientFactory createFactory(TransportClientFactory factory) {
        return new HttpClientFactory() {
            @Override
            public HttpClient newClient() {
                return new RetrableHttpClient(factory);
            }
        };
    }
}
